module.exports = app => {
    const express = require('express')
    const AdminUser = require('../../models/AdminUser')
    const assert = require('http-assert')
    const jwt = require('jsonwebtoken')
    const router = express.Router({
        mergeParams: true
    })


    // 保存资源
    router.post('/', async (req, res) => {
        const model = await req.Model.create(req.body)
        res.send(model)
    })

    // 资源列表
    router.get('/', async (req, res) => {
        const queryOptoins = {}
        let { pageSize, pageNum } = req.query;
        if (req.Model.modelName === 'Category') {
            queryOptoins.populate = 'parent'
        }
        if (pageSize !== '' && pageNum !== '') {
            pageSize = parseInt(pageSize)
            pageNum = parseInt(pageNum)
            queryOptoins.skip = (pageNum - 1) * pageSize
            queryOptoins.limit = pageSize
        }
        const items = await req.Model.find().setOptions(queryOptoins)
        res.send(items)
    })

    // 获取资源
    router.get('/:id', async (req, res) => {
        const model = await req.Model.findById(req.params.id)
        res.send(model)
    })

    // 更新资源
    router.put('/:id', async (req, res) => {
        const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
        res.send(model)
    })

    // 删除资源
    router.delete('/:id', async (req, res) => {
        await req.Model.findByIdAndDelete(req.params.id)
        res.send({
            success: true
        })
    })


    // 资源中间件
    const resourceMiddleware = require('../../middleware/resource')
    const authMiddleware = require('../../middleware/auth')
    app.use('/admin/api/rest/:resource', authMiddleware(), resourceMiddleware(), router)

    const multer = require('multer')
    const upload = multer({
        dest: __dirname + '/../../uploads'
    })

    // 上传图片路由
    app.use('/admin/api/upload', authMiddleware(), upload.single('file'), async (req, res) => {
        const file = req.file;
        file.url = `http://localhost:3000/uploads/${file.filename}`
        res.send(file)
    })

    // 处理登录
    app.use('/admin/api/login', async (req, res) => {
        const { username, password } = req.body;
        // 验证用户名
        const user = await AdminUser.findOne({ username }).select('+password')
        assert(user, 422, '用户不存在');
        // 验证密码
        const isValid = require('bcrypt').compareSync(password, user.password)
        assert(isValid, 422, '密码错误');
        // 返回token
        const token = jwt.sign({ id: user._id }, require('../../config/jwt').secret)
        res.send({
            token,
            message: '登录成功'
        })
    })

    // 错误处理中间件
    app.use((err, req, res, next) => {
        res.status(err.statusCode || 500).send({
            message: err.message
        })
    })
}
